package timing.ukulele.portal.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import timing.ukulele.common.data.ResponseData;
import timing.ukulele.data.portal.view.SysTenantUserVO;
import timing.ukulele.data.portal.view.SysTenantVO;
import timing.ukulele.facade.portal.mvc.SysTenantControllerFacade;
import timing.ukulele.portal.convertor.TenantConvertor;
import timing.ukulele.portal.persistent.SysTenant;
import timing.ukulele.portal.service.SysTenantService;

import java.util.Date;
import java.util.List;
import java.util.Set;

@RestController
public class SysTenantController  implements SysTenantControllerFacade {

    private final SysTenantService service;

    public SysTenantController(SysTenantService service) {
        this.service = service;
    }

    @Override
    public ResponseData<SysTenantVO> get(Long id) {
        if (id == null || id <= 0) {
            return ResponseData.paramError();
        }
        SysTenant po = this.service.getById(id);
        if (po != null) {
            SysTenantVO vo = TenantConvertor.INSTANCE.p2v(po);
            return ResponseData.success(vo);
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData<List<SysTenantVO>> get(Set<Long> list) {
        List<SysTenant> poList = this.service.lambdaQuery().in(SysTenant::getId, list).list();
        if (CollectionUtils.isEmpty(poList))
            return ResponseData.success();
        List<SysTenantVO> voList = TenantConvertor.INSTANCE.p2vList(poList);
        return ResponseData.success(voList);
    }

    @Override
    public ResponseData<SysTenantVO> add(String currentUser, SysTenantVO vo) {
        if (vo == null || vo.getId() != null) {
            return ResponseData.paramError();
        }
        SysTenant po = TenantConvertor.INSTANCE.v2p(vo);
        this.service.save(po);
        vo.setId(po.getId());
        return ResponseData.success(vo);
    }

    @Override
    public ResponseData<Boolean> delete(String currentUser, Long id) {
        if (id == null || id <= 0) {
            return ResponseData.paramError();
        }
        this.service.lambdaUpdate().eq(SysTenant::getId, id)
                .set(SysTenant::getDeleted, Boolean.TRUE)
                .set(SysTenant::getUpdateBy, currentUser)
                .set(SysTenant::getUpdateTime, new Date()).update();
        return ResponseData.success(Boolean.TRUE);
    }

    @Override
    public ResponseData<SysTenantVO> edit(String currentUser, SysTenantVO vo) {
        if (vo == null || vo.getId() == null) {
            return ResponseData.paramError();
        }
        SysTenant po = TenantConvertor.INSTANCE.v2p(vo);
        this.service.saveOrUpdate(po);
        return ResponseData.success(vo);
    }

    @Override
    public ResponseData<List<SysTenantVO>> currentUserTenantList(String currentUser) {
        return ResponseData.success(this.service.getUserTenantListByUsername(currentUser));
    }

    @Override
    public ResponseData<List<SysTenantVO>> userTenantByUsername(String username) {
        return ResponseData.success(this.service.getUserTenantListByUsername(username));
    }

    @Override
    public ResponseData<List<SysTenantVO>> userTenantByUserId(Long userId) {
        return ResponseData.success(this.service.getUserTenantListByUserId(userId));
    }

    @Override
    public ResponseData<SysTenantVO> checkUserTenant(String username, Long userId, Long tenantId) {
        if (!StringUtils.hasText(username) && tenantId == null) {
            return ResponseData.paramError();
        }
        Boolean success = this.service.checkUserTenant(username, userId, tenantId);
        if (!success) {
            return ResponseData.success();
        }
        SysTenant tenant = this.service.getById(tenantId);
        SysTenantVO vo = null;
        if (tenant != null) {
            vo = TenantConvertor.INSTANCE.p2v(tenant);
        }
        return ResponseData.success(vo);
    }

    @Override
    public ResponseData<Boolean> addUserTenant(SysTenantUserVO vo) {
        if (vo == null || !StringUtils.hasText(vo.getUsername()) || vo.getTenantId() == null || vo.getUserId() == null) {
            return ResponseData.paramError();
        }
        return this.service.addTenantUser(vo);
    }

    @Override
    public ResponseData<Boolean> deleteUserTenant(Long userId, Long tenantId) {
        this.service.deleteTenantUser(userId, tenantId);
        return ResponseData.success(Boolean.TRUE);
    }

    @GetMapping("/page/{current}/{size}")
    public ResponseData<IPage<SysTenantVO>> getPage(@PathVariable(name = "current") int current,
                                                    @PathVariable(name = "size") int size,
                                                    @RequestParam(name = "deleted", required = false) Boolean deleted,
                                                    @RequestParam(value = "name", required = false) String name) {
        if (size == 0) {
            size = 10;
        }
        if (current == 0) {
            current = 1;
        }
        return ResponseData.success(this.service.getPage(current, size, deleted, name));
    }

    /**
     * 租户的用户列表
     *
     * @param current  当前页
     * @param size     每页大小
     * @param tenantId 租户id
     * @param username 用户名
     * @return 用户列表
     */
    @GetMapping("/page/user/{tenantId}/{current}/{size}")
    public ResponseData<IPage<SysTenantUserVO>> getTenantUserPage(@PathVariable(name = "current") int current,
                                                                  @PathVariable(name = "size") int size,
                                                                  @PathVariable(name = "tenantId") Long tenantId,
                                                                  @RequestParam(value = "username", required = false) String username) {
        if (size == 0) {
            size = 10;
        }
        if (current == 0) {
            current = 1;
        }
        return ResponseData.success(this.service.getTenantUserPage(current, size, username, tenantId));
    }

    /**
     * 用户租户列表
     *
     * @param current  当前页
     * @param size     每页大小
     * @param userId   用户id
     * @param username 用户名
     * @return 用户列表
     */
    @GetMapping("/page/tenant/{userId}/{current}/{size}")
    public ResponseData<IPage<SysTenantUserVO>> getUserTenantPage(@PathVariable(name = "current") int current,
                                                                  @PathVariable(name = "size") int size,
                                                                  @PathVariable(name = "userId", required = false) Long userId,
                                                                  @RequestParam(value = "username", required = false) String username) {
        if (userId == null && !StringUtils.hasText(username))
            return ResponseData.paramError( "不能同时为空");
        if (size == 0) {
            size = 10;
        }
        if (current == 0) {
            current = 1;
        }
        return ResponseData.success(this.service.getUserTenantPage(current, size, username, userId));
    }
}
